<?php
/**
 * Display a Frame
 */
use Nawa\MedicalStudy;
use Fox\Core\Errors;
use Fox\Html\Input;
use Fox\Generator;
use Fox\Html\Html;
use Fox\Html\Button;
use Fox\Popup;
use Fox\Msg;
use Nawa\Customer;
use Fox\Common\Contact;
use Fox\Dao\SqlFragment;
use Fox\Document\Type;
use Fox\Html\Input\File;
use Fox\Html\DropList;
use Fox\Html\Block;
use Fox\Html\Screen;

$xview = Xview::instance();
$screen = new Screen('sDocument','import');
$block = new Block('bDocument');
// Doc Type
$finder = new Type();
$types = $finder->find(new SqlFragment("category = ?",array(Customer::DOC_CATEGORY_EMPLOYEE)));
$block->add(new DropList('doctype',false,false,true))->options($types,'doctype','description');
$block->add(new File('filename',true));
$block->add(new Input('customerid',true,$xview->val('customerid')))->hidden();
$block->noLegend();
$screen->add($block);
if($screen->submitted())
{
	$fields = $screen->get();
	if(!$screen->errors())
	{
		try {
			$customer = Fox\Dao::load(Customer::className(),$fields['customerid']);
			$fileName = \Xview::moveFileToServer();
			$data['filename'] = $fileName['filename'];
			$data['destination'] = _TEMP_;
			$data['language'] = "FR";
			$data['doctype'] = $fields['doctype'];
			$data['physicalname'] = $fileName['physicalname'];
			// Create Document Object
			$document = new \Fox\Document();
			$document->setFields($data);
			$document->create();
			$resData['docid'] = $document->getId();
			$resData['customerid'] = $customer->getId();
			$documentLink = new Fox\Common\Customer\Document();
			$documentLink->setFields($resData);
			$customer->replaceDocuments($documentLink);
			$customer->prepareUpdate(Customer::CHANGE_DOCUMENTS);
			$customer->update();
			// Build external link if necessary 
			$msid = $xview->val('msid');
			if(!empty($msid)) {
				// Add the document to the parnter inside the Medical Study
				$ms = $xview->component('medicalstudies','object',array('msid' => $msid));
				if($ms->exists()) {
					try {
						$partner = $ms->findPartners($msid.':'.$resData['customerid']);
						if($partner->exists()) {
							$partner->setFields(array('docid' => $resData['docid']));
							$ms->replacePartners($partner);
							$ms->prepareUpdate(MedicalStudy::CHANGE_ADD_DOCUMENT_TO_PARTNER);
							$ms->update();
						}
						
					} catch(Fox\Object\Exception\Save $e) {
						Errors::generateMessage($e);
					}
				}
			}
			// Add document to the search engine
			/*
			 $searchEngine = new \Fox\SearchEngine();
			 $searchEngine->add($document,$customer->getId(),Customer::classname());
			 */

		}
		catch (Fox\Object\Exception\Save $e)
		{
			Errors::generateMessage($e);
		}

	}
}
$popup = new Popup('pAddDocument',Msg(Msg::BUNDLE,Msg::TITLE_ADD_DOCUMENT),$screen);
$caller = $xview->val('caller','MC_documents');
$screen->ajaxUpload(Generator::ajaxReload($caller));
echo $popup->display();